<script setup name="File">
import { getFileList, delFile, downloadFile, globalSearch } from '@/api/subject/subject'
import UploadFileDlg from './components/UploadFileDlg'
import FileDataDlg from './components/FileDataDlg'
import GlobalSearchDlg from './components/GlobalSearchDlg'
import PreviewVideoDlg from './components/PreviewVideoDlg.vue'
import dayjs from 'dayjs'
const { proxy } = getCurrentInstance()

const workType = ref('')
const { sys_work_type } = proxy.useDict('sys_work_type')
const { sys_file_type } = proxy.useDict('sys_file_type')
const route = useRoute()

const total = ref(0)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const selectName = ref('')
const loading = ref(true)
const multiple = ref(true)
const uploadDlgRef = ref(null)
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  fileName: undefined,
  fileType: undefined,
  projectId: route.params.projectId
})
const fileList = ref([])
const getList = () => {
  let fileTypes
  if (queryParams.value.fileType) {
    fileTypes = queryParams.value.fileType.split(';')
  }
  const params = {
    ...queryParams.value,
    workType: workType.value,
    fileTypes
  }
  getFileList(params).then(response => {
    fileList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}
const handleUpload = () => {
  console.log(233333)
  uploadDlgRef.value.showDlg()
}

const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  multiple.value = !selection.length
  single.value = selection.length !== 1
  selectName.value = selection.map(item => item.fileName)
}
function resetQuery () {
  proxy.resetForm('queryRef')
  queryParams.value.pageNum = 1
  getList()
}
const formatTime = (time) => {
  return time ? dayjs.unix(time).format('YYYY-MM-DD HH:mm:ss') : ''
}
const viewData = (row) => {
  const imageMimeTypes = ['jpg', 'png', 'gif', 'ibmp', 'webp', 'jpeg']
  const dataResultsTypes = ['dat', 'txt', 'xlsx', 'xls']
  const videoTypes = ['mp4', 'webm', 'ogg', 'avi', 'mpeg']
  if (imageMimeTypes.includes(row.fileType)) {
    // 查看图片
    previewImage(row).then(url => {
      proxy.viewerApi({
        options: {
          inline: true,
          button: true, // 右上角按钮
          navbar: true, // 底部缩略图
          title: true, // 当前图片标题
          toolbar: {
            zoomIn: true,
            zoomOut: true,
            oneToOne: false,
            reset: true,
            prev: false,
            play: {
              show: true,
              size: 'large'
            },
            next: false,
            rotateLeft: true,
            rotateRight: true,
            flipHorizontal: true,
            flipVertical: true
          }, // 底部工具栏
          tooltip: true, // 显示缩放百分比
          movable: true, // 是否可以移动
          zoomable: true, // 是否可以缩放
          rotatable: true, // 是否可旋转
          scalable: true, // 是否可翻转
          transition: true, // 使用 CSS3 过度
          fullscreen: true, // 播放时是否全屏
          keyboard: true // 是否支持键盘
        },
        images: [url]
      })
    })
  }
  if (dataResultsTypes.includes(row.fileType)) {
    // 查看数据
    proxy.$refs.dataDlg.show(row)
  }
  if (videoTypes.includes(row.fileType)) {
    previewImage(row).then(res => {
      const fileInfo = {
        fileName: row.fileName,
        fileUrl: res
      }
      proxy.$refs.videoDlg.show(fileInfo)
    })
  }
}
const previewImage = (row) => {
  return new Promise((resolve, reject) => {
    const params = {
      workType: row.workType,
      fileName: row.fileName
    }
    downloadFile(params).then(res => {
      resolve(res.url)
    }).catch((err) => {
      console.log('下载失败:' + err)
    })
  })
}
const handleDownload = (row) => {
  const params = {
    workType: row.workType,
    fileName: row.fileName
  }
  downloadFile(params).then(res => {
    const fileUrl = res.url
    const link = document.createElement('a')
    link.href = fileUrl
    link.download = row.fileName
    link.click()
  })
}

const handleDelete = (row) => {
  console.log(row)
  selectName.value = row.fileName ? [row.fileName] : selectName.value
  const infoIds = row.id ? [row.id] : ids.value

  const params = {
    fileIds: infoIds,
    fileNames: selectName.value,
    directory: row.workType
  }
  proxy.$modal.confirm('是否确认删除文件名称为"' + selectName.value + '"的文件?').then(function () {
    return delFile(params)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => {})
}
const handleGlobalSearch = () => {
  proxy.$refs.searchDlg.show()
}
const handleSearch = async (form) => {
  console.log(1122, form)
  const params = {
    pneumaticForm: form.pneumaticForm.map(({ id, ...rest }) => rest)
  }
  console.log(form.fileType)
  const pageParams = {
    pageNum: 1,
    pageSize: 999,
    fileType: form.fileType
  }
  const res = await globalSearch(params, pageParams)
  proxy.$refs.searchDlg.closeDlg()
  fileList.value = res.rows
  total.value = res.total
}
const changeWork = (val) => {
  proxy.resetForm('queryRef')
  queryParams.value.pageNum = 1
  getList()
}
watch(() => sys_work_type.value, (newVal) => {
  if (newVal && newVal.length > 0) {
    workType.value = newVal[0]?.value || ''
    getList()
  } else {
    console.error('sys_work_type 为空或未定义')
  }
}, { immediate: true })

onMounted(() => {
  getList()
})
</script>

<template>
  <div class="app-container">
    <div class="work-container">
      <el-radio-group
        v-model="workType"
        @change="changeWork"
      >
        <el-radio-button
          v-for="item in sys_work_type"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-radio-group>
    </div>

    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item
        label="文件名称"
        prop="fileName"
      >
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名称"
          clearable
          style="width: 240px;"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item
        label="文件类型"
        prop="fileType"
      >
        <el-select
          placeholder="请选择文件类型"
          v-model="queryParams.fileType"
          style="width: 240px"
        >
          <el-option
            v-for="item in sys_file_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <!--        <el-input
          v-model="queryParams.projectCode"
          placeholder="请输入项目编号"
          clearable
          style="width: 240px;"
          @keyup.enter="handleQuery"
        />-->
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="Search"
          @click="handleQuery"
        >
          搜索
        </el-button>
        <el-button
          icon="Refresh"
          @click="resetQuery"
        >
          重置
        </el-button>
        <el-button
          icon="Search"
          @click="handleGlobalSearch"
        >
          全局检索
        </el-button>
      </el-form-item>
    </el-form>
    <el-row
      :gutter="10"
      class="mb8"
    >
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="upload"
          @click="handleUpload"
          v-hasPermi="['file:upload']"
        >
          上传文件
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['file:delete']"
        >
          删除
        </el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @query-table="getList"
      />
    </el-row>
    <el-table
      ref="logininforRef"
      v-loading="loading"
      :data="fileList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        label="文件名称"
        align="center"
        prop="fileName"
      />
      <el-table-column
        label="文件类型"
        align="center"
        prop="fileType"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="研究类型"
        align="center"
        prop="workType"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <dict-tag
            :options="sys_work_type"
            :value="scope.row.workType"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="所属任务"
        align="center"
        prop="projectName"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <el-tag type="primary">
            {{ scope.row.projectName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="所属专题"
        align="center"
        prop="subjectName"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <el-tag type="info">
            {{ scope.row.subjectName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="上传时间"
        align="center"
        prop="createTime"
      >
        <template #default="scope">
          <span>{{ formatTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        prop="opt"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="view"
            @click="viewData(scope.row)"
            v-hasPermi="['file:view']"
          >
            查看
          </el-button>
          <el-button
            link
            type="warning"
            icon="Files"
            @click="handleDownload(scope.row)"
            v-hasPermi="['file:download']"
          >
            下载
          </el-button>
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['file:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <UploadFileDlg
      ref="uploadDlgRef"
      :project-id="route.params.projectId"
      :work-type="workType"
      @on-success="getList"
    />
    <FileDataDlg ref="dataDlg" />
    <GlobalSearchDlg
      ref="searchDlg"
      @submit-params="handleSearch"
    />
    <PreviewVideoDlg ref="videoDlg" />
  </div>
</template>

<style scoped lang="scss">
.work-container {
  margin-bottom: 16px;
}
</style>
